<script setup>
import { ref, reactive, watch, onBeforeUnmount, shallowRef, onMounted } from 'vue'
import { UploadFilled, InfoFilled, Plus,Search } from '@element-plus/icons-vue'
import { ElMessage, } from 'element-plus'
import { setImg } from '../../utils/setImg'
import { getProductApi, getProductCategoryApiAll, getShoppingDetail, putProductApi, deleteProductApi, addProductApi } from '../../api/require'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import Tag from '../../pages/Tag.vue'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
const input1 = ref('');
const input2 = ref('');
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const shopList = ref([]);
const flag = ref(0);
const putId = ref('');
const total = ref()
//控制弹出框
const dialogFormVisible = ref(false)
const formLabelWidth = '60px'
const dialogVisible = ref(false);
const currentData = ref({});
const form = reactive({
  name: '',
  desc: '',
  category: '',
  price: '',
  amount: '',
  content: ''
})
const allCategory = ref([])
//获取商品分类列表
getProductCategoryApiAll().then(
  res => {
    allCategory.value = res.data.data;
    //添加索引
  }
)
const currentPage = ref(1)
//获取数据
const getData = (page = 1) => {
  getProductApi(page,input1.value,input2.value).then(
    res => {
      console.log(res.data);
      total.value = res.data.total
      shopList.value = res.data.data;
      //添加索引
      shopList.value.forEach((item, index) => {
        item.index = index + 1;
      })
    }
  )
}
//重置
const resData = () => {
  form.name = '';
  imageUrl.value = '';
  form.desc = '';
  form.category = '';
  form.price = '';
  form.amount = '';
  valueHtml.value = '';
}
getData()
//删除
const handleDelete = (id) => {
  deleteProductApi(id).then(
    res => {
      //console.log(res);
      getData()
    }
  )
}
const savaData = () => {
  //console.log(form.name);
  if (!form.name || !form.category) {
    //console.log(form.name, form.category);
    ElMessage({
      message: '输入不能为空',
      type: 'warning',
    })
  } else {
    if (flag.value == 1) {
      //修改
      //console.log(putId.value, form.category);
      //console.log(valueHtml.value);
      putProductApi(putId.value, {
        name: form.name,
        coverImage: imageUrl.value,
        desc: form.desc,
        category: form.category.id,
        content: valueHtml.value,
        price: form.price,
        amount: form.amount
      }).then(
        res => {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          resData();
          getData();
          dialogFormVisible.value = false;
          flag.value == 0;
        })
    } else {
      addProductApi({
        name: form.name,
        coverImage: imageUrl.value,
        desc: form.desc,
        category: form.category,
        content: valueHtml.value,
        price: form.price,
        amount: form.amount
      }).then(
        res => {
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          //console.log(form.category);
          resData();
          getData();
          dialogFormVisible.value = false
        }
      )
    }
    //console.log(file.url);
  }
}
const imageUrl = ref('');
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = response.data;
  //console.log(response);
  //console.log(uploadFile);
}
//修改
const handleClick = async (id) => {
  //根据id获取数据
  //console.log(id);
  currentData.value = shopList.value.filter(item => item.id == id);
  const tempContent = await getShoppingDetail(id)
  putId.value = id;
  console.log(currentData.value[0]);
  dialogFormVisible.value = true;
  form.name = currentData.value[0].name;
  imageUrl.value = currentData.value[0].coverImage ? setImg(currentData.value[0].coverImage) : 'http://127.0.0.1:5173/index.jpg';
  form.desc = currentData.value[0].desc;
  form.price = currentData.value[0].price;
  form.amount = currentData.value[0].amount;
  form.category = currentData.value[0].category;
  valueHtml.value = tempContent.data.data.content;
  //修改flag为1
  flag.value = 1;
}
//分页器
const handleCurrentChange = page => {
  //获取这一页数据展示
  //console.log(page);
  currentData.value = page;
  getData(page)
}
watch(dialogFormVisible, (val) => {
  //console.log(val);
  if (!val) {
    resData();
  }
})
//取消
const toSearch = ()=>{
  getData();
  input1.value = '';
  input2.value = '';
}
</script>
<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>
      <router-link :to="{name:'Index'}">商品管理</router-link>
    </el-breadcrumb-item>
    <el-breadcrumb-item>商品</el-breadcrumb-item>
  </el-breadcrumb>
  <h1 style="margin-top: 10px;">商品</h1>
  <Tag></Tag>
  <!-- 表格 -->
  <div class="demo-input-size">
    <el-input v-model="input1" class="w-50 m-2" size="large" placeholder="请输入名字搜索" :suffix-icon="Search" />
    <el-select v-model="input2" placeholder="请选择">
          <el-option v-for="item in allCategory" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
    <el-button type="primary" @click="toSearch" id="btn">查询</el-button>
  </div>
  <div class="table-main">
    <div class="table-main-head">
      <span>商品</span>
      <el-button class="right" type="success" :icon="Plus" @click="dialogFormVisible = true" size="default">增加
      </el-button>
    </div>
    <el-table :default-sort="{ prop: 'index', order: 'ascending' }" :data="shopList" stripe style="width: 100%" border>
      <el-table-column prop="index" sortable label="序号" align="center" width="100" />
      <el-table-column prop="name" label="名字" align="center" width="280" />
      <el-table-column prop="category.name" label="分类" align="center" width="280" />
      <el-table-column prop="" label="图片" align="center" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <img :src="scope.row.coverImage?setImg(scope.row.coverImage):'index.jpg'" class="imgLeft" align="center"
              alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" align="center" width="100" />
      <el-table-column prop="amount" label="库存" align="center" width="100" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleClick(scope.row.id)">修改</el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled" icon-color="#626AEF"
            title="你是否确认删除?" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" title="商品编辑">
    <el-form :model="form">
      <el-form-item label="名字" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="简介" :label-width="formLabelWidth">
        <el-input v-model="form.desc" type="textarea" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类" :label-width="formLabelWidth">
        <el-select v-model="form.category" placeholder="请选择">
          <el-option v-for="item in allCategory" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload class="avatar-uploader" action="http://localhost:1337/api/v1/common/upload_file"
          :show-file-list="false" :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl?setImg(imageUrl):'index.jpg'" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="价格" :label-width="formLabelWidth">
        <el-input v-model="form.price" type="number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="库存" size="small" :label-width="formLabelWidth">
        <el-input v-model="form.amount" type="number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="详情" size="small" :label-width="formLabelWidth">
        <div style="border: 1px solid #ccc; width: 610px; display: flex; flex-direction: column;" >
          <Toolbar style="border-bottom: 1px solid #ccc;flex: 1; height: 200px;" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
          <Editor style="height: 500px; overflow: scroll;" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" v-html="valueHtml"/>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="savaData">提交</el-button>
      </span>
    </template>
  </el-dialog>
  <el-pagination :background="true" v-model:currentPage="currentPage" layout="prev, pager, next"
    @current-change="handleCurrentChange" :total="total" />
</template>
<style scoped lang="scss">
.table-main {
  background-color: #fff;
}

img {
  width: 60px;
}
.demo-input-size{
  display: flex;
  padding: 10px 0;
  padding-left: 40px;
  background-color: #fff;
  margin: 10px 0;
  position: relative;
  .m-2{
    width: 30%;
    margin-right: 40px;
  }
  #btn{
    position: absolute;
    right: 30px;
    top: 15px;
  }
}
.table-main-head {
  padding: 20px 0;
  padding-left: 20px;
}

.right {
  float: right;
  margin-right: 10px;
}

.imgLeft {
  margin-left: 50px;
}
</style>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 150px;
}

.el-pagination {
  margin-top: 20px;
  padding-left: 500px;
}
</style>